package cn.itcast.wushangxiantu.Fragment.guozhanshenqin;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;

import java.io.IOException;

import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.Activity.Login;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ChuangJianGuoJiaFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ChuangJianGuoJiaFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Context context;
    private View view;
    private ViewHolder viewHolder;

    public ChuangJianGuoJiaFragment(Context context) {
        this.context = context;
    }

    public ChuangJianGuoJiaFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ChuangJianGuoJiaFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ChuangJianGuoJiaFragment newInstance(String param1, String param2) {
        ChuangJianGuoJiaFragment fragment = new ChuangJianGuoJiaFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_chuang_jian_guo_jia, container, false);
        viewHolder=new ViewHolder(view);
        return view;
    }

    class ViewHolder {
        public View rootView;
        public EditText etName;
        public EditText etContent;
        public Button btnChuangJian;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.etName = (EditText) rootView.findViewById(R.id.etName);
            this.etContent = (EditText) rootView.findViewById(R.id.etContent);
            this.btnChuangJian = (Button) rootView.findViewById(R.id.btnChuangJian);
            btnChuangJian.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (etName.getText().toString().trim().equals("")){
                        ToastUtil.toast(context,"不允许为空");
                        return;
                    }
                    if (etContent.getText().toString().trim().equals("")){
                        ToastUtil.toast(context,"好歹说点什么把");
                        return;
                    }
                    getGuoJiaChuangJianWpNumber();
                }
            });
        }
        public void GeneralDialog(String head, final String content, final int number) {
            /**
             * 普通对话框
             * 1标题
             * 2内容
             */
            AlertDialog dialog;
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle(head)
                    .setMessage(content)
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (number==1){
                                setGuoJia(Login.getUser().getUsernumber(),Login.getUser().getPassword(),etName.getText().toString().trim(),etContent.getText().toString().trim());
                            }
                            dialogInterface.dismiss();
                        }
                    });
            dialog = builder.create();
            dialog.show();
        }

        /**
         * 创建国家
         * @param usernumber 首领账号
         * @param password
         * @param trim 国家名
         * @param trim1 国家公告
         */
        private void setGuoJia(String usernumber, String password, String trim, String trim1) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "need=setGuoJia" + "&userNumber=" + usernumber + "&passWord=" + password + "&name=" + trim + "&title=" + trim1, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                        try {
                            Log.v("setGuoJia",e.getMessage());
                        }catch (Exception e1){

                        }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res=response.body().string();
                    Log.v("setGuoJia", res);
                    Message message=new Message();
                    User user=new Gson().fromJson(res,User.class);
                    message.obj=user;
                    message.what=2;
                    handler.sendMessage(message);
                }
            });
        }

        private void getGuoJiaChuangJianWpNumber() {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "need=getGuoJiaChuangJianWpNumber", new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("getnumber",e.getMessage());
                    }catch (Exception e1){
                    }
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res=response.body().string();
                    Log.v("getnumber",res);
                    Message message=new Message();
                    User user=new Gson().fromJson(res,User.class);
                    message.obj=user;
                    message.what=1;
                    handler.sendMessage(message);
                }
            });
        }
        Handler handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message message) {
                switch (message.what){
                    case 1:
                        User user= (User) message.obj;
                        if (null!=user){
                            GeneralDialog("创建详情",user.getStw(),1);
                        }else {
                            ToastUtil.toast(context,"服务器出现异常");
                        }
                        break;
                    case 2:
                         user= (User) message.obj;
                        if (null!=user){
                            GeneralDialog("创建详情",user.getStw(),0);
                        }else {
                            ToastUtil.toast(context,"服务器出现异常");
                        }
                        break;
                }
                return false;
            }
        });
    }
}